package comits.business.tiers.orm.hibernate;
import java.io.File;

import org.apache.axis2.context.MessageContext;
import org.apache.axis2.description.AxisService;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.context.internal.ManagedSessionContext;

public class HibernateSession {
	
	private static final SessionFactory sessionFactory;
	//public static final ThreadLocal session = new ThreadLocal();
	      
	//Initialisation de la session
	
		static
		{
			try
		    {
				/*Configuration config = new Configuration();
		        MessageContext msgCtx = MessageContext.getCurrentMessageContext();
		        AxisService myService = msgCtx.getAxisService();  
		        config.addJar(new File(myService.getClassLoader().getResource("mapping.jar").getFile()));
		        sessionFactory= config.buildSessionFactory();*/
		        
				// Creation de la session factory grâce au fichier de config
		         sessionFactory = new Configuration().configure("comits/business/tiers/orm/hibernate/hibernate.cfg.xml").buildSessionFactory();
		    }
		     catch(Throwable ex)
		     {
		    	 System.err.println("Initial SessionFactorycreation failed. " + ex);
		         throw new ExceptionInInitializerError(ex);
		     }
		}

	
	       
	//Getter de l'attribut sessionFactory
	public static SessionFactory getSessionFactory()
	{
		return sessionFactory;
	}

	//Methode pour créer et récupérer la session en cours d'utilisation
	public static final ThreadLocal<Session> session = new ThreadLocal<Session>();
	        
	public static Session currentSession()
	throws HibernateException
	{
		Session s = (Session) session.get();
		// Ouvre une nouvelle Session, si ce Thread n'en a aucune
		if (s == null) {
			s = sessionFactory.openSession();
			s.setFlushMode(FlushMode.MANUAL);
			ManagedSessionContext.bind(s);
			s.beginTransaction();
			session.set(s);
		}
		return s;
	}	   	 
	
	protected void commitTransaction(Session session)
	{
		ManagedSessionContext.unbind(sessionFactory);
	    session.flush();
	    session.getTransaction().commit();
	    session.close();
	}

	public static void closeSession()
	throws HibernateException
	{
		Session s = (Session) session.get();
		session.set(null);
		if (s != null)
			s.close();
	}
}
